package seatiger.tomcat.catalina.startup;

import seatiger.tomcat.catalina.*;
import seatiger.tomcat.util.StringManager;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 基础监听器
 */
public abstract class BaseConfig<T extends Container> implements LifecycleListener {

    protected T container;

    protected static final StringManager sm = StringManager.getManager(Constants.PACKAGE_STARTUP);

    Function<LifecycleEvent,T> function;

    public BaseConfig(Function<LifecycleEvent,T> function){
        this.function = function;
    }

    protected Consumer<Container> getConsumer(){
        return c -> {};
    }

    public void lifecycleEvent(LifecycleEvent event) {
        try {
            container = function.apply(event);
            getConsumer().accept(container);
        }catch (ClassCastException e){
            log(sm.getString("contextConfig.cce",new Object[]{event.getLifecycle()}), e);
            return;
        }
        if (event.getType().equals(Lifecycle.START_EVENT)){
            start(container);
        }
        if (event.getType().equals(Lifecycle.STOP_EVENT)){
            stop(container);
        }
    }

    public abstract void start(T container);

    /**
     * 监听容器停止
     * @param container
     */
    public abstract void stop(T container);

    protected void log(String message, Throwable throwable) {
        Logger logger = container != null ?  container.getLogger() : null;
        if (logger != null){
            logger.log(getSimpleName()+"[" +  container.getName() + "] " + message, throwable);
        }else {
            System.out.println(getSimpleName()+"" +  container.getName() + "]: " + message);
            System.out.println("" + throwable);
            throwable.printStackTrace(System.out);
        }
    }

    protected void log(String message) {
        Logger logger =  container != null ?  container.getLogger() : null;
        if (logger != null){
            logger.log(getSimpleName()+"[" +  container.getName() + "]: " + message);
        } else{
            System.out.println(getSimpleName()+"[" +  container.getName() + "]: " + message);
        }
    }
    private String getSimpleName(){
        return this.getClass().getSimpleName();
    }
}
